#include "process_pool.h"
int main(int argc,char* argv[])
{
    if(argc!=4)
    {
        printf("./process_pool_server IP PORT PROCESS_NUM\n");
        return -1;
    }
    int process_num=atoi(argv[3]);
    process_data_t *p=(process_data_t*)calloc(process_num,sizeof(process_data_t));
    make_child(p,process_num);
    int socket_fd;//equal sfd;
    tcp_init(&socket_fd,argv[1],argv[2]);
    printf("socket_fd=%d\n",socket_fd);
    int epfd=epoll_create(1);
    int ret=epoll_add(epfd,socket_fd);
    SELFFUNC_ERR_CHECK(ret,"epoll_add")
    int i;
    for(i=0;i<process_num;i++)
    {
        ret=epoll_add(epfd,p[i].fd);
        SELFFUNC_ERR_CHECK(ret,"epoll_add")
    }
    int new_fd,j;
    int ready_fd_num;
    struct epoll_event *evs=(struct epoll_event *)calloc(process_num+1,sizeof(struct epoll_event));
    struct sockaddr_in client_addr;
    char flag;
    while(1)
    {
        ready_fd_num=epoll_wait(epfd,evs,process_num+1,-1);
        for(i=0;i<process_num;i++)
        {
            if(evs[i].data.fd==socket_fd)
            {
                //create new_fd;
                bzero(&client_addr,sizeof(client_addr));
                socklen_t addr_len=sizeof(client_addr);
                new_fd=accept(socket_fd,(struct sockaddr*)&client_addr,&addr_len);
                printf("%s %d is connect\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
                for(j=0;j<process_num;j++)
                {
                    if(0==p[j].busy)
                    {
                        write(p[j].fd,&new_fd,sizeof(new_fd));
                        p[j].busy=1;
                        printf("child %d is busy\n",p[j].pid);
                        break;
                    }
                }
            }
            for(j=0;j<process_num;j++)
            {
                if(evs[i].data.fd==p[j].fd)
                {
                    read(p[j].fd,&flag,sizeof(flag));
                    p[j].busy=0;
                    printf("child %d is not busy\n",p[j].pid);
                    break;
                }
            }
        }
    }
    return 0;
}